package com.lyb.events;


import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import com.lyb.app.App;
import com.lyb.bean.AppInfo;
import com.lyb.bean.UserSmsInfoBean;
import com.lyb.config.Constant;
import com.lyb.jpush.TagAliasOperatorHelper;
import com.lyb.ui.authentication.bean.CallLogBean;
import com.lyb.ui.authentication.bean.ContactBean;
import com.lyb.ui.authentication.db.DatabaseManager;
import com.lyb.ui.lend.contract.UploadContentsContract;
import com.lyb.ui.lend.presenter.UploadContentsPresenter;
import com.lyb.ui.login.activity.LoginActivity;
import com.lyb.ui.login.contract.LoginOutContract;
import com.lyb.ui.login.presenter.LoginOutPresenter;
import com.lyb.ui.main.MainActivity;
import com.lyb.ui.my.bean.UserInfoBean;
import com.lyb.util.CallLogUtil;
import com.lyb.util.ContactsUploadUtil;
import com.lyb.util.ConvertUtil;
import com.lyb.util.LogUtils;
import com.lyb.util.ServiceUtil;
import com.lyb.util.SmsUtil;
import com.lyb.util.SpUtil;
import com.lyb.util.StringUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


public class EventController implements UploadContentsContract.View {

    private static volatile EventController instance = null;
    private UploadContentsPresenter mUploadPresenter;
    private Context                 mContext;
    private List<ContactBean>       mContactList;

    private EventController() {

    }

    /******
     * 获取单例
     *
     * @return
     */
    public static EventController getInstance() {
        if (instance == null) {
            synchronized (EventController.class) {

                if (instance == null) {
                    instance = new EventController();
                }

            }
        }
        return instance;
    }


    /**********
     * eventBus 事件派发
     *
     * @param event
     */
    public void handleMessage(final BaseEvent event) {
        if (event.getUiEvent() == null) {
            //登陆
            if (event instanceof LoginEvent) {
                saveUserInfo(((LoginEvent) event).getBean(), ((LoginEvent) event).getContext(), true);
                setJPushAlia(((LoginEvent) event).getBean());
                if (((LoginEvent) event).isToNext()) {
                    EventBus.getDefault().post(new RefreshUIEvent(UIBaseEvent.EVENT_LOGIN));//是点哪个页面跳转的登录，登录后就跳转到点击的页面
                }
            } else if (event instanceof LogoutEvent)//退出
            {
                logOut((LogoutEvent) event);
            } else if (event instanceof LoginNoRefreshUIEvent) {//启动app时保存用户数据
                saveUserInfo(((LoginNoRefreshUIEvent) event).getBean(), ((LoginNoRefreshUIEvent) event).getContext(),
                        true);
            } else if (event instanceof LoanEvent) {
                mUploadPresenter = new UploadContentsPresenter();
                mContext = ((LoanEvent) event).getContext();
                mUploadPresenter.init(this);
                sendAPP();
            } else if (event instanceof UploadEvent) {
                mUploadPresenter = new UploadContentsPresenter();
                mContext = ((UploadEvent) event).getContext();
                mUploadPresenter.init(this);
                sendAPP();
            }
        }
    }

    private void setJPushAlia(UserInfoBean userInfo) {
        if (userInfo != null) {
            TagAliasOperatorHelper.getInstance().setJPushAlias(userInfo.getUsername());
        }
    }

    private void sendAPP() {
        if (mUploadPresenter == null) {
            mUploadPresenter = new UploadContentsPresenter();
            mUploadPresenter.init(this);
        }
        Observable.create(new Observable.OnSubscribe<List<AppInfo>>() {
            @Override
            public void call(Subscriber<? super List<AppInfo>> subscriber) {
                try {
                    subscriber.onNext(getAppInfoList(mContext));
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<AppInfo>>() {
                    @Override
                    public void call(List<AppInfo> appInfos) {
//                        mUploadPresenter.toUploadContents(mUploadPresenter.TYPE_APP, ConvertUtil.toJsonString
//                                (appInfos));
                    }
                });
    }

    private void sendSMS() {
        if (mUploadPresenter == null) {
            mUploadPresenter = new UploadContentsPresenter();
            mUploadPresenter.init(this);
        }
        Observable.create(new Observable.OnSubscribe<List<UserSmsInfoBean>>() {
            @Override
            public void call(Subscriber<? super List<UserSmsInfoBean>> subscriber) {
                try {
                    subscriber.onNext(SmsUtil.getSmsInfoList(mContext));
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<UserSmsInfoBean>>() {
                    @Override
                    public void call(List<UserSmsInfoBean> userSmsInfoBeen) {
//                        mUploadPresenter.toUploadContents(mUploadPresenter.TYPE_SMS, ConvertUtil.toJsonString
//                                (userSmsInfoBeen));
                    }
                });
    }


    /**********
     * 退出
     *
     * @param event
     */
    private void logOut(LogoutEvent event) {

        EventBus.getDefault().post(new RefreshUIEvent(UIBaseEvent.EVENT_LOGOUT));
        Intent intent = new Intent(event.getApplicationContext(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        event.getContext().startActivity(intent);
        Intent loginIntent = new Intent(App.getContext(), LoginActivity.class);
        String uName = SpUtil.getString(Constant.CACHE_TAG_USERNAME);
        loginIntent.putExtra("tag", StringUtil.changeMobile(uName));
        loginIntent.putExtra("phone", uName);
        loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        App.getContext().startActivity(loginIntent);
        clearLoginStatus(App.getContext(), event.getTAG());
        ServiceUtil.cancelAlarmManager(App.getContext());
    }


    /************
     * 清除登录状态
     */
    public static void clearLoginStatus(Context context, int tag) {
        SpUtil.putString(Constant.CACHE_TAG_SESSIONID, "");
        SpUtil.putString(Constant.CACHE_TAG_UID, "");
        //SpUtil.putString(Constant.SHARE_TAG_USERNAME, "");
        App.getConfig().setUserInfo(null);
        //清除cookie
        CookieSyncManager.createInstance(context);
        CookieManager cm = CookieManager.getInstance();
        cm.removeAllCookie();
        CookieSyncManager.getInstance().sync();
        if (tag == 0) {
            LoginOutPresenter loginOutPresenter = new LoginOutPresenter();
            loginOutPresenter.init(new LoginOutContract.View() {
                @Override
                public void loginOutSuccess() {
                }

                @Override
                public void showLoading(String content) {
                }

                @Override
                public void stopLoading() {
                }

                @Override
                public void showErrorMsg(String msg, String type) {
                }
            });
            loginOutPresenter.loginOut();
        }
    }

    /********
     * 登陆成功后保存用户信息
     *
     * @param userInfo
     */
    private void saveUserInfo(UserInfoBean userInfo, Context context, boolean isUpload) {
        if (userInfo != null) {
            SpUtil.putString(Constant.CACHE_TAG_USERNAME, userInfo.getUsername());
            SpUtil.putString(Constant.CACHE_TAG_UID, userInfo.getUid() + "");
            SpUtil.putString(Constant.CACHE_TAG_SESSIONID, userInfo.getSessionid());

            App.getConfig().setUserInfo(userInfo);
            CookieSyncManager.createInstance(context);
            CookieManager cm = CookieManager.getInstance();
            String cookie = "SESSIONID=" + userInfo.getSessionid() + ";UID=" + userInfo.getUid();
            cm.setCookie(App.getConfig().getBaseUrl(), cookie);
            CookieSyncManager.getInstance().sync();
            cacheUserInfo(userInfo, context);
            try {
                if (isUpload) {
                    if (mContext == null) {
                        mContext = context;
                    }
                    sendAPP();
                }
            } catch (RuntimeException e) {
                e.printStackTrace();
                LogUtils.loge("通话记录获取异常");
            }

            //判断service是否开启
            try {
                if (!ServiceUtil.isServiceRunning(context, "com.lyb.ui.my.service.UploadPOIService")) {
                    ServiceUtil.invokeTimerPOIService(context);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            EventBus.getDefault().post(new FragmentRefreshEvent(UIBaseEvent.EVENT_LOGIN));
        }
    }

    /*************
     * 上传联系人
     */
    public void uploadContact(final Context context) {
        if (mUploadPresenter == null) {
            mUploadPresenter = new UploadContentsPresenter();
            mUploadPresenter.init(this);
        }

        if (context == null) {
            //            mContext = App.getContext();
            return;
        }

        Observable.create(new Observable.OnSubscribe<List<ContactBean>>() {
            @Override
            public void call(Subscriber<? super List<ContactBean>> subscriber) {
                try {
                    mContactList = ContactsUploadUtil.getAllContacts(context);
                    subscriber.onNext(mContactList);
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<ContactBean>>() {
                    @Override
                    public void call(List<ContactBean> contactBeen) {
                        if (contactBeen != null) {
                            String data = ConvertUtil.toJsonString(contactBeen);
//                            mUploadPresenter.toUploadContents(mUploadPresenter.TYPE_CONTACT, data);
                        }
                    }
                });
    }

    /**
     * 获取手机安装的app列表
     * @param context
     * @return
     */
    private List<AppInfo> getAppInfoList(Context context) {
        // 获取手机中所有已安装的应用，并判断是否系统应用
        ArrayList<AppInfo> appList = new ArrayList<>(); //用来存储获取的应用信息数据，手机上安装的应用数据都存在appList里
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);

        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            //判断是否系统应用
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                //非系统应用
                AppInfo tmpInfo = new AppInfo();
                tmpInfo.setAppName(packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString());
                tmpInfo.setPackageName(packageInfo.packageName);
                tmpInfo.setVersionCode(packageInfo.versionCode);
                tmpInfo.setVersionName(packageInfo.versionName);
                if (App.getConfig().getUserInfo() != null) {
                    tmpInfo.setUserId(App.getConfig().getUserInfo().getUid());
                }
                appList.add(tmpInfo);
            } else {
                //系统应用　　　　　　　　
            }
        }
        return appList;
    }

    /**
     * 保存用户信息到本地缓存
     * @param bean
     * @param context
     */
    private void cacheUserInfo(UserInfoBean bean, Context context) {
        SpUtil.putString(Constant.CACHE_TAG_USERNAME, bean.getUsername());
        SpUtil.putString(Constant.CACHE_TAG_REAL_NAME, bean.getRealname());
        String userListStr = SpUtil.getString(Constant.CACHE_USERLIST_KEY);
        List userList = null;
        if (StringUtil.isBlank(userListStr)) {
            userList = new ArrayList();
        } else {
            userList = ConvertUtil.StringToList(userListStr);
        }

        if (userList.indexOf(bean.getUsername()) < 0) {
            userList.add(bean.getUsername());
        }
        SpUtil.putString(Constant.CACHE_USERLIST_KEY, ConvertUtil.ListToString(userList));
    }

    @Override
    public void uploadSuccess(String type) {
        if (type == mUploadPresenter.TYPE_CALL_LOG) {
            Logger.t("upload_content").e("通话记录上传成功");
        } else if (type == mUploadPresenter.TYPE_APP) {
            Logger.t("upload_content").e("应用列表上传成功");
            try {
                uploadContact(mContext);
            } catch (RuntimeException e) {
                e.printStackTrace();
                LogUtils.loge("联系人获取异常");
            }
        } else if (type == mUploadPresenter.TYPE_CONTACT) {
            Logger.t("upload_content").e("联系人列表上传成功");
            if (mContactList != null) {
                //上传成功后保存数据库 下次会先对比数据库手机号 然后只上传新增的手机号（联系人）
                DatabaseManager mDb = new DatabaseManager(App.getContext());
                mDb.open();
                for (ContactBean bean : mContactList) {
                    mDb.addContact(bean.getId(), bean.getMobile(), bean.getName(), bean.getStatus(), bean.getUser_id());
                }
                mDb.close();
            }
            sendSMS();
        } else if (type == mUploadPresenter.TYPE_SMS) {
            Logger.t("upload_content").e("短信列表上传成功");
            sendCallLog();
        }
    }

    @Override
    public void showLoading(String content) {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorMsg(String msg, String type) {
        if (type == mUploadPresenter.TYPE_CALL_LOG) {
            Logger.t("upload_content").e("通话记录上传失败");
        } else if (type == mUploadPresenter.TYPE_APP) {
            Logger.t("upload_content").e("应用列表上传失败");
            try {
                uploadContact(mContext);
            } catch (RuntimeException e) {
                e.printStackTrace();
                LogUtils.loge("联系人获取异常");
            }
        } else if (type == mUploadPresenter.TYPE_CONTACT) {
            Logger.t("upload_content").e("联系人列表上传失败");
            sendSMS();
        } else if (type == mUploadPresenter.TYPE_SMS) {
            Logger.t("upload_content").e("短信列表上传失败");
            sendCallLog();
        }
    }

    private void sendCallLog() {
        if (mUploadPresenter == null) {
            mUploadPresenter = new UploadContentsPresenter();
            mUploadPresenter.init(this);
        }
        Observable.create(new Observable.OnSubscribe<List<CallLogBean>>() {
            @Override
            public void call(Subscriber<? super List<CallLogBean>> subscriber) {
                try {
                    subscriber.onNext(CallLogUtil.getCallLog(mContext));
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<CallLogBean>>() {
                    @Override
                    public void call(List<CallLogBean> callLogBeen) {
                        String callLog = ConvertUtil.toJsonString(callLogBeen);
//                        mUploadPresenter.toUploadContents(mUploadPresenter.TYPE_CALL_LOG, callLog);
                    }
                });
    }
}
